<script setup lang="ts">
import { nextTick, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import FormProduct from '@/components/form/FormProduct.vue'
import { productMyList, productSave, productDelete } from '@/api/interface/web/product'
import { typeAll } from '@/api/interface/web/type'
import JsBarcode from 'jsbarcode'
import html2Canvas from 'html2canvas'
import { validatePlusFloatWithTwo } from '@/utils/validate'

const doc: any = document

const fullscreenLoading = ref(false)

const searchForm = ref<any>({
  rangeDate: [],
})

const baseTableRef = ref()

const typeDatas = ref<any[]>([])

const getTypeAll = async () => {
  typeAll({}).then((res: any) => {
    typeDatas.value = formatterType(res, '')
  })
}
const formatterType = (data: any, parentId: any) => {
  data.forEach((v: any, i: any) => {
    data[i] = {
      label: v.name,
      value: v.id,
      parentId,
      children: formatterType(v.children, v.id),
    }
  })
  return data
}
getTypeAll()

const conditionMethod = () => {
  const cond: any = {}
  Object.keys(searchForm.value).map((key) => {
    if (searchForm.value[key] || searchForm.value[key] === 0) {
      if (key === 'rangeDate') {
        if (searchForm.value[key]) {
          cond['createTime'] = searchForm.value[key][0]
          cond['updateTime'] = searchForm.value[key][1]
        }
      } else if (key === 'type') {
        findTypeData(cond, searchForm.value[key], typeDatas.value)
      } else {
        cond[key] = searchForm.value[key]
      }
    }
  })

  return cond
}

const findTypeData = (result: any, id: any, data: any) => {
  data.forEach((v: any) => {
    if (v.value == id) {
      if (v.parentId) {
        result['firstType'] = v.parentId
        result['secondType'] = v.value
      } else {
        result['firstType'] = v.value
      }
    } else {
      findTypeData(result, id, v.children)
    }
  })
}

const handleSearch = () => {
  baseTableRef.value.refresh()
}

const handleResetSearch = () => {
  searchForm.value = {
    rangeDate: [],
  }
  baseTableRef.value.refresh()
}

// 删除
const handleDelete = (row: any) => {
  const { id } = row
  ElMessageBox.confirm('确定删除商品?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    autofocus: false,
  }).then(() => {
    productDelete({ id })
      .then(() => {
        ElMessage({
          message: '删除成功!',
          type: 'success',
        })
      })
      .finally(() => {
        baseTableRef.value.refreshStay()
      })
  })
}

// 添加编辑
const dialogVisible = ref(false)

const addEditData = ref<any>({})

const addEditStatus = ref('add')

const formUserRef = ref()

const handleAdd = () => {
  addEditStatus.value = 'add'
  addEditData.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  addEditStatus.value = 'edit'
  addEditData.value = row
  dialogVisible.value = true
}

const handleDialogClose = () => {
  dialogVisible.value = false
}

const handleDialogSubmit = () => {
  formUserRef.value.submitForm().then((data: any) => {
    if (data) {
      fullscreenLoading.value = true
      const { id, type } = data
      if (type.length) {
        if (type.length == 2) {
          data.firstType = type[0]
          data.secondType = type[1]
        } else {
          data.firstType = type[0]
          data.secondType = ''
        }
      }
      productSave(data)
        .then(() => {
          ElMessage({
            message: '操作成功!',
            type: 'success',
          })
          dialogVisible.value = false

          if (id) {
            baseTableRef.value.refreshStay()
          } else {
            baseTableRef.value.refreshStay()
          }
        })
        .finally(() => {
          fullscreenLoading.value = false
        })
    }
  })
}

const blurPrice = (row: any) => {
  if (!validatePlusFloatWithTwo(row.price)) {
    ElMessage.error('请输入正整数或两位小数的数字!')
    return
  }
  fullscreenLoading.value = true
  productSave(row)
    .then(() => {
      ElMessage({
        message: '操作成功!',
        type: 'success',
      })

      baseTableRef.value.refreshStay()
    })
    .finally(() => {
      fullscreenLoading.value = false
    })
}

const codeInfo: any = ref()
const handleCode = (row: any) => {
  // window.open(
  //   `${window.location.origin}/code?name=${row.name}&code=${row.code}&styleCode=${row.styleCode}&color=${row.color}&productSize=${row.productSize}&price=${row.price}`,
  // )
  codeInfo.value = row
  const options = {
    format: 'CODE128', //选择要使用的条形码类型
    // format: 'EAN13', // 格式
    height: 80,
    // text: "覆盖显示的文本",
    fontSize: 16,
    // background: '#ccc',
    lineColor: 'black',
  }
  JsBarcode(barcodeRef.value, row.code, options)

  nextTick(() => {
    html2Canvas(doc.querySelector('#code-box')).then((canvas) => {
      const dataURL = canvas.toDataURL('image/png')
      if (dataURL !== '') {
        const a = doc.createElement('a')
        a.download = row.name
        a.href = dataURL
        a.click()
      }
    })
  })
}

const barcodeRef = ref(null)
</script>

<template>
  <BasePageWrapper v-loading.fullscreen="fullscreenLoading">
    <BasePage>
      <template #title>商品管理</template>
      <template #toolbar>
        <el-button type="primary" @click="handleAdd">
          <template #icon>
            <el-icon><Plus /></el-icon>
          </template>
          新增
        </el-button>
      </template>
      <template #searchbar>
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="商品名：">
            <el-input v-model="searchForm.name" placeholder="请输入商品名" />
          </el-form-item>
          <el-form-item label="条形码：">
            <el-input v-model="searchForm.code" placeholder="请输入条形码" />
          </el-form-item>
          <el-form-item label="分类:" prop="type">
            <el-tree-select
              v-model="searchForm.type"
              :data="typeDatas"
              :render-after-expand="false"
              show-checkbox
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="info" text bg @click="handleResetSearch">
              <template #icon>
                <el-icon><Refresh /></el-icon>
              </template>
              重置
            </el-button>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><Search /></el-icon>
              </template>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <BaseTable
        ref="baseTableRef"
        :init-table-method="productMyList"
        :condition-method="conditionMethod"
      >
        <!-- <el-table-column
          type="index"
          label="编号"
          align="center"
          header-align="center"
          width="60"
        ></el-table-column> -->
        <el-table-column prop="first_name" label="一级类目" show-overflow-tooltip></el-table-column>
        <el-table-column
          prop="second_name"
          label="二级类目"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="name"
          min-width="130"
          label="商品名称"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="code"
          label="条形码"
          show-overflow-tooltip
          min-width="130"
        ></el-table-column>
        <el-table-column prop="styleCode" label="款号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="layout" label="版型" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sex" label="性别" show-overflow-tooltip></el-table-column>
        <el-table-column prop="colorCode" label="色号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="color" label="颜色" show-overflow-tooltip></el-table-column>
        <el-table-column prop="productSize" label="尺码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="year" label="年份" show-overflow-tooltip></el-table-column>
        <el-table-column prop="season" label="季节" show-overflow-tooltip></el-table-column>
        <el-table-column prop="cityDate" label="上市日期" show-overflow-tooltip></el-table-column>
        <el-table-column prop="weight" label="重量" show-overflow-tooltip></el-table-column>
        <el-table-column prop="price" label="商品价" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.price"
              style="width: 70px"
              placeholder="输入价格"
              @blur="blurPrice(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="buyingPrice" label="进货价" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.buyingPrice"
              style="width: 70px"
              placeholder="输入价格"
              @blur="blurPrice(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="inventory" label="库存" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.inventory"
              style="width: 70px"
              placeholder="输入库存"
              @blur="blurPrice(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110">
          <template #default="scope">
            <el-button type="primary" link @click="handleCode(scope.row)">生成条形码</el-button>
            <div>
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </BaseTable>
    </BasePage>
  </BasePageWrapper>
  <BaseDialog v-model="dialogVisible" width="35%">
    <template #title>{{ addEditStatus === 'add' ? '新增' : '编辑' }}</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="handleDialogSubmit">保存</el-button>
    </template>
    <FormProduct ref="formUserRef" :data="addEditData" :status="addEditStatus"></FormProduct>
  </BaseDialog>

  <div
    id="code-box"
    class="code-wrapper"
    style="position: fixed; left: 150px; top: 5550px; background-color: #fff"
  >
    <div v-if="false" class="code-item-wrapper">
      <div class="code-item">商品名: {{ codeInfo?.name }}</div>
      <div class="code-item">款号: {{ codeInfo?.styleCode }}</div>
      <div class="code-item">颜色: {{ codeInfo?.color }}</div>
      <div class="code-item">尺码: {{ codeInfo?.productSize }}</div>
      <div class="code-item">商品价: {{ codeInfo?.price }} 元</div>
    </div>
    <svg ref="barcodeRef" class="code"></svg>
  </div>
</template>

<style lang="scss" scoped>
.page-content-container {
  @include rect(100%, 100%);
  @include flex(row, space-between, flex-start);
  .left {
    @include rect(220px, 100%);
    box-sizing: border-box;
    padding-bottom: 24px;
  }
  .right {
    @include rect(calc(100% - 240px), 100%);
    :deep(.role-tag) {
      margin-right: 10px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .icon-text-box {
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-text {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 24px;
        cursor: pointer;
        .icon {
          margin-right: 5px;
          font-size: 16px;
        }
        .text {
          width: 2em;
        }
        .text.add {
          min-width: 4em;
        }
      }
      .icon-text:last-child {
        margin-right: 0;
      }
      .icon-text.info {
        color: var(--theme-color);
      }
      .icon-text.delete {
        color: #f56c6c;
      }
    }
  }
}

.code-wrapper {
  width: 6.5cm;
  height: 3.3cm;
  border: 1px solid #333;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .code {
    width: 100%;
  }
}
</style>
